import { handleHonest, messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { Collapse , Form, Row, Col, Popconfirm} from 'antd'
const Panel =Collapse.Panel;

import Condition from 'components/condition'
const { If, ElseIf, Else } = Condition;

import beepTimerService from 'containers/setting/beep-timer/beep-timer.service'
import 'styles/setting/beep-timer/beef-info.scss'
import constants from "share/constants";


class BeepInfo extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      info: {},
      paramsData: {},
      requestList: [],
      businessCardName: '', //商务卡类型名称
      consumeTypes: '', //商务卡消费数据类型名称
      periodTypes: '', //商务卡账单期数
      invoiceLabels: [],//费用包含标签
      invoiceStatus: [],//费用报销状态
      expenseStatus: [], //报销单状态
      expenseForms: [], //报销单表单
      honestInfo: {}
    }
  }

  componentWillMount(){
    this.initData(this.props.applyData)
  }

  componentWillReceiveProps(nextProps) {
    this.initData(nextProps.applyData)
  }

  initData = (data) => {
    this.setState({
      info: data,
      paramsData: JSON.parse(data.params || '{}')
    }, () => {
      const { type } = this.props;
      const { paramsData, info } = this.state;
      if (type === "traver") {
        this.getBillsName(paramsData)
      }
      if (type === "business-card") {
        this.getBusinessCardTypeName(paramsData);
        this.getBusinessCardConsumeTypes(paramsData);
        this.getBusinessCardPeriodTypes(paramsData)
      }
      if (type === "expense-report") {
        this.getInvoiceLabels(paramsData.labels);
        this.getInvoiceStatus(paramsData.invoiceStatus);
        this.getHonestInfo(info.id);
        paramsData.invoiceStatus.indexOf(1) > -1 && this.getExpenseStatus(paramsData);
      }
      if (type === "expense-invoice") {
        this.getExpenseForms(paramsData.formOids);
        this.getHonestInfo(info.id);
      }
      if (type === "repayment") {
        this.getHonestInfo(info.id)
      }
    })
  };

  //获取表单名称
  getBillsName = (paramsData) =>{
    let requestList = [];
    let isAllInvalid = true;
    paramsData.formOIDs && beepTimerService.getByOIDs(paramsData.formOIDs).then(res => {
      res.data.rows.map((item, i) => {
        item.valid && (isAllInvalid = false);
        i === (res.data.rows.length - 1) ? requestList.push(<span key={i + 1} style={{color:item.valid ? '#666' : '#ccc'}}>{item.formName}</span>) :
          requestList.push(<span key={i + 1} style={{color:item.valid ? '#666' : '#aaa'}}>{item.formName}，</span>)
      });
      if(!requestList.length || isAllInvalid){
        requestList.push(<a key={0} className="choose-request" onClick={(e) => this.handleEdit(e)}>{messages('setting.key105'/*请选择申请单*/)}/*请选择申请单*/</a>)
      }
      this.setState({ requestList })
    })
  };

  //TODO: 获取商务卡类型名称
  getBusinessCardTypeName = (paramsData) =>{
    paramsData.bankCardTypes.map(type => {
      if(type === 'CMBC') {
        this.setState({ businessCardName: messages('setting.key106'/*招行商务卡*/) })
      }
    })
  };

  //TODO: 获取商务卡消费数据类型名称
  getBusinessCardConsumeTypes = (paramsData) => {
    let consumeTypes = [];
    paramsData.consumeTypes.map(item => {
      if(item === "BANK_TRAN_NOT_CREATED_INVOICE") {
        consumeTypes.push(messages('setting.key67'/*未生成费用的消费*/))
      } else if(item === "BANK_TRAN_NOT_REFERENCED_REPORT") {
        consumeTypes.push(messages('setting.key107'/*已生成未关联报销单的费用*/))
      } else if(item === "BANK_TRAN_NOT_PASSED_REPORT") {
        consumeTypes.push(messages('setting.key69'/*已生成报销单未提交的费用*/))
      }
    });
    this.setState({ consumeTypes: consumeTypes.join(', ') })
  };

  //TODO: 获取商务卡账单期数
  getBusinessCardPeriodTypes = (paramsData) => {
    let periodTypes = [];
    paramsData.billingPeriodTypes.map(item => {
      if (item === 'CURRENT_MONTH') {
        periodTypes.push(messages('setting.key70'/*本月账单*/))
      } else if (item === 'LAST_MONTH') {
        periodTypes.push(messages('setting.key71'/*上月账单*/))
      }
    });
    this.setState({ periodTypes: periodTypes.join(', ') })
  };

  getInvoiceLabels = (value) => {
    let result = [];
    beepTimerService.getInvoiceLabels().then(res => {
      value.map(item => {
        result.push(res.data.filter(ele => ele.id === item)[0].name);
      });
      this.setState({invoiceLabels:result});
    });
  };

  getInvoiceStatus = (value) => {
    let result = [];
    value.map(item => {
      item === 0 && result.push(messages('setting.key72'/*未关联报销单*/));
      item === 1 && result.push(messages('setting.key73'/*已关联报销单*/));
    });
    this.setState({invoiceStatus:result});
  };

  getExpenseStatus = (value) => {
    let expense = constants.expenseStatus;
    let result = [];
    value.status.map((item,index) => {
      let temp = `${item}${item === '1001' ? value.rejectType[index] : ''}`;
      result.push(expense.filter(ele => ele.value === temp)[0].label);
    });
    this.setState({expenseStatus: result});
  };

  getHonestInfo = id => {
    beepTimerService.getHonestList(id).then(res => {
      this.setState({ honestInfo: res.data.id ? res.data : {} });
    })
  };

  //获取报销单表单
  getExpenseForms = (value) => {
    const { company } = this.props;
    let result = [];
    beepTimerService.getExpenseList(company.companyOID).then(res => {
      value.map(oid => {
        result.push(res.data.filter(item => item.formOID === oid)[0].formName);
      });
      this.setState({ expenseForms: result });
    });
  };


  handleEdit = e => {
    const { honestInfo } = this.state;
    e.stopPropagation();
    let temp = Object.assign(this.props.applyData, {conditionId: honestInfo.id});
    this.props.onEdit(temp);
  };

  handleDelete = () =>{
    this.props.onDelete(this.props.applyData);
  };

  render() {
    const { type } = this.props;
    const { info, paramsData, requestList, businessCardName, consumeTypes, periodTypes, expenseStatus, invoiceStatus,
      invoiceLabels, expenseForms, honestInfo } = this.state;
    let remindTypes = [];
    paramsData.remindTypes && paramsData.remindTypes.map(item => {
      remindTypes.push(item === 'APP' ? messages('setting.key65'/*APP消息*/) : messages('setting.key66'/*邮件提醒*/))
    });
    paramsData.repaymentRemindTypes && paramsData.repaymentRemindTypes.map(item => {
      remindTypes.push(item === 'APP' ? messages('setting.key65'/*APP消息*/) : messages('setting.key66'/*邮件提醒*/))
    });
    let repaymentTarget = [];
    paramsData.repaymentRemindPersonTypes && paramsData.repaymentRemindPersonTypes.map(item => {
      switch (item){
        case 'CREATED_BY':
          repaymentTarget.push(messages('setting.key1302')/*申请人*/);
          break;
        case 'PAYEE':
          repaymentTarget.push(messages('setting.key1870')/*收款人（仅限员工）*/);
          break;
        case 'FINANCE':
          repaymentTarget.push(messages('setting.key960')/*财务*/);
          break;
        default:
          break;
      }
    });
    let target = (
      (type === "expense-report" || type === "expense-invoice") ?
        (paramsData.target === 0 ? messages('setting.key74'/*本人*/) :
          (paramsData.target === 1 ? messages('setting.key75'/*直属领导*/) : messages('setting.key76'/*部门经理*/))) : ''
    );
    let panelHeader = (
      <div className="beep-info-header">
        <span>{paramsData.title || '-'}</span>
        <span className="beep-info-operation">
            <a onClick={this.handleEdit}>{messages('common.edit')/*编辑*/}</a>
            <span className="ant-divider"/>
            <Popconfirm onConfirm={this.handleDelete}
                        onClick={e => e.stopPropagation()}
                        title={messages('setting.key23'/*你确定要删除这条数据吗?*/)}>
              <a>{messages('common.delete')/*删除*/}</a>
            </Popconfirm>
        </span>
      </div>
    );
    let remindTip = {
      __html: messages(type === 'traver' ? 'setting.key1481' : 'setting.key1482', {
        arg1: `<span class="remind-date">${paramsData.remindDay}</span>`
      })
    };
    return (
      <div className="beep-info">
        <Collapse bordered={false}>
          <Panel header={panelHeader}>
            <div className="beep-info-content">
              <div className="content-info">
                <Condition>
                  <If value={type === "expense-report"}>
                    {paramsData.target === 0 ?
                      messages('setting.key1439', {arg1: paramsData.content}/*您有（费用发生日期）发生的费用，{arg1}*/) :
                      messages('setting.key1440', {arg1: paramsData.content}/*(费用所属人姓名/工号）有（费用发生日期 ）发生的费用，{arg1}*/)}
                  </If>
                  <ElseIf value={type === "expense-invoice"}>
                    {paramsData.target === 0 ? messages('setting.key1977',{arg1:paramsData.content})/*（若已交票，请忽略此提醒）您的【报销单号码】报销单，{arg1}*/ : messages('setting.key1978',{arg1:paramsData.content})/*(单据所属人姓名/工号）的【报销单号码】报销单，{arg1}*/}
                  </ElseIf>
                  <Else>
                    {paramsData.content}
                  </Else>
                </Condition>
              </div>

              {type ==="regularly" && (
                <Row style={{marginLeft:24}}>
                  <Col span={8}>{messages('setting.key81'/*发送日期*/)}：{info.month}-{info.date}</Col>
                  <Col span={8}>{messages('setting.key82'/*发送时间*/)}{/*发送时间*/}：{info.hour + ':00'}</Col>
                </Row>
              )}

              {type ==="traver" && (
                <div className="traver-borrow-style">
                  <Row>
                    <Col span={2} className="title">{messages('setting.key81'/*发送日期*/)}{/*发送日期*/}：</Col>
                    <Col span={10}>
                      <span dangerouslySetInnerHTML={remindTip}></span>
                    </Col>
                    <Col span={2} className="title">{messages('setting.key82'/*发送时间*/)}{/*发送时间*/}：</Col>
                    <Col span={6}>{info.hour + ':00'}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key84'/*适用单据*/)}{/*适用单据*/}：</Col>
                    <Col span={22}>{requestList}</Col>
                  </Row>
                </div>
              )}

              {type ==="business-card" && (
                <div className="business-card-style">
                  <Row>
                    <Col span={2} className="title">{messages('setting.key81'/*发送日期*/)}{/*发送日期*/}：</Col>
                    <Col span={6}>{messages('setting.key85'/*每月*/)}{/*每月*/}<span className="remind-date"> {info.date} </span>{messages('setting.key86'/*日*/)}{/*日*/}<span className="remind-date"> {info.hour} </span>{messages('setting.key110'/*时*/)}{/*时*/}</Col>
                    <Col span={2} className="title">{messages('setting.key88'/*提醒方式*/)}{/*提醒方式*/}：</Col>
                    <Col span={6}>{remindTypes.length ? remindTypes.join('，') : '-'}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key89'/*商务卡*/)}{/*商务卡*/}：</Col>
                    <Col span={18}>{businessCardName}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key111'/*消费数据*/)}{/*消费数据*/}：</Col>
                    <Col span={18}>{consumeTypes}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key91'/*账单期数*/)}{/*账单期数*/}：</Col>
                    <Col span={18}>{periodTypes}</Col>
                  </Row>
                </div>
              )}
              {
                type === "expense-report" && (
                  <div className="expense-report-style">
                    <Row>
                      <Col span={2} className="title">{messages('setting.key112'/*发送日期：*/)}</Col>
                      <Col span={6}>{messages('setting.key1442',{arg1:paramsData.remindDay}/*费用发生{arg1}天后提醒员工*/)}</Col>
                      <Col span={2} className="title">{messages('setting.key113'/*发送时间：*/)}</Col>
                      <Col span={6}>{info.hour + ':00'}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key114'/*提醒费用：*/)}</Col>
                      <Col span={18}>{messages('setting.key115'/*【费用标签】*/)}：{invoiceLabels.join('，')}；{messages('setting.key116'/*【关联报销单】*/)}：{invoiceStatus.join('，')}；{expenseStatus.length > 0 ? messages('setting.key117'/*【报销单状态】：*/) : ''}{expenseStatus.join('，')}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key118'/*提醒方式：*/)}</Col>
                      <Col span={18}>{remindTypes.length ? remindTypes.join('，') : '-'}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key119'/*提醒对象：*/)}</Col>
                      <Col span={18}>{target}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key2216')/*信用规则：*/}</Col>
                      <Col span={18}>
                        {
                          honestInfo.id ?
                            `${honestInfo.ruleCondition} - ${honestInfo.ruleConditionCode}（${honestInfo.modelCode} - ${honestInfo.modelName} ${handleHonest(honestInfo)}）`
                            : '-'
                        }
                      </Col>
                    </Row>
                  </div>
                )
              }
              {
                type === "repayment" && (
                  <div>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key112'/*发送日期：*/)}</Col>
                      <Col span={6}>
                        {
                          paramsData.repaymentRemindBaseDateType === 'BEFORE_PLANED_REPAYMENT_DATE' ? messages('setting.key1482',{arg1:paramsData.differenceDate})/*预计还款日期前{arg1}天提醒员工*/ :
                            paramsData.repaymentRemindBaseDateType === 'AFTER_APPROVED_DATE' ? messages('setting.key1877',{arg1:paramsData.differenceDate})/*审批通过日期后{arg1}天提醒员工*/ : messages('setting.key1878',{arg1:paramsData.differenceDate})/*审核通过日期后{arg1}天提醒员工*/
                        }
                      </Col>
                      <Col span={2} className="title">{messages('setting.key113'/*发送时间：*/)}</Col>
                      <Col span={6}>{info.hour + ':00'}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key118'/*提醒方式：*/)}</Col>
                      <Col span={18}>{remindTypes.length ? remindTypes.join('，') : '-'}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key119'/*提醒对象：*/)}</Col>
                      <Col span={18}>{repaymentTarget.length ? repaymentTarget.join(',') : '-'}</Col>
                    </Row>
                    <Row>
                      <Col span={2} className="title">{messages('setting.key2216')/*信用规则：*/}</Col>
                      <Col span={18}>
                        {
                          honestInfo.id ?
                            `${honestInfo.ruleCondition} - ${honestInfo.ruleConditionCode}（${honestInfo.modelCode} - ${honestInfo.modelName} ${handleHonest(honestInfo)}）`
                            : '-'
                        }
                      </Col>
                    </Row>
                  </div>
                )
              }
              {type === "expense-invoice" && (
                <div className="expense-report-style">
                  <Row>
                    <Col span={2} className="title">{messages('setting.key112'/*发送日期：*/)}</Col>
                    <Col span={9}>{messages('setting.key1980',{arg1:paramsData.remindDay})/*在报销单首个打印节点后{arg1}天后提醒员工*/}</Col>
                    <Col span={2} className="title">{messages('setting.key113'/*发送时间：*/)}</Col>
                    <Col span={6}>{info.hour + ':00'}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key118'/*提醒方式：*/)}</Col>
                    <Col span={18}>{remindTypes.length ? remindTypes.join('，') : '-'}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key119'/*提醒对象：*/)}</Col>
                    <Col span={18}>{target}</Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key2216')/*信用规则：*/}</Col>
                    <Col span={18}>
                      {
                        honestInfo.id ?
                          `${honestInfo.ruleCondition} - ${honestInfo.ruleConditionCode}（${honestInfo.modelCode} - ${honestInfo.modelName} ${handleHonest(honestInfo)}）`
                          : '-'
                      }
                    </Col>
                  </Row>
                  <Row>
                    <Col span={2} className="title">{messages('setting.key84'/*适用单据*/)}：</Col>
                    <Col span={18}>{expenseForms.join('，')}</Col>
                  </Row>
                </div>
              )}
            </div>
          </Panel>
        </Collapse>
      </div>
    )
  }
}

BeepInfo.propTypes = {
  type: React.PropTypes.string.isRequired,  //选择类型 traver, business-card, regularly, expense-report, repayment, expense-invoice
  applyData: React.PropTypes.object.isRequired,
  onEdit: React.PropTypes.func,    //编辑
  onDelete: React.PropTypes.func,  //删除
};

BeepInfo.defaultProps = {
  onEdit: () => {},
  onDelete: () => {},
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
  }
}

const wrappedBeepInfo = Form.create()(BeepInfo);

export default connect(mapStateToProps)(wrappedBeepInfo);
